import router from '@/router'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 白名单路由
const whiteList = ['/login', '/404']

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  // 设置页面标题
  document.title = to.meta.title || '电信客户流失预警系统'
  
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()
  const hasToken = getToken()
  
  if (hasToken) {
    if (to.path === '/login') {
      // 已登录则重定向到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 检查是否已获取用户信息
      const hasUserInfo = userStore.userInfo && Object.keys(userStore.userInfo).length > 0
      
      if (hasUserInfo) {
        // 检查是否有权限访问该页面
        if (hasPermission(to, userStore.userInfo)) {
          next()
        } else {
          next('/404')
        }
      } else {
        try {
          // 获取用户信息和权限
          await userStore.getUserInfo()
          await permissionStore.getPermissions()
          
          // 基于权限生成可访问路由
          const accessRoutes = await permissionStore.generateRoutes(userStore.userInfo.role)
          
          // 动态添加可访问路由
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })
          
          // 确保路由完成加载
          next({ ...to, replace: true })
        } catch (error) {
          // 出错时重置令牌并重定向到登录页
          await userStore.resetToken()
          console.error(error)
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 白名单路由可直接访问
      next()
    } else {
      // 其他页面重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

// 检查页面权限
function hasPermission(route, userInfo) {
  if (route.meta && route.meta.requiresAuth === false) {
    return true
  }
  
  if (!userInfo || !userInfo.role) {
    return false
  }
  
  // 检查角色权限
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(userInfo.role)
  }
  
  // 检查具体权限
  if (route.meta && route.meta.permissions) {
    const userPermissions = userInfo.permissions || []
    return route.meta.permissions.some(permission => 
      userPermissions.includes(permission) || userPermissions.includes('*')
    )
  }
  
  return true
}

// 权限指令
export const permission = {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    const userInfo = userStore.userInfo
    
    if (value) {
      const hasPermission = checkPermission(value, userInfo)
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  }
}

// 检查权限
function checkPermission(value, userInfo) {
  if (!userInfo || !userInfo.role) {
    return false
  }

  // 管理员拥有所有权限
  if (userInfo.role === 'admin') {
    return true
  }

  if (typeof value === 'string') {
    // 检查单个权限或角色
    const userPermissions = userInfo.permissions || []
    const userRole = userInfo.role

    // 检查权限
    if (userPermissions.includes(value) || userPermissions.includes('*')) {
      return true
    }

    // 检查角色
    if (userRole === value) {
      return true
    }

    return false
  }

  if (Array.isArray(value)) {
    // 检查权限或角色数组（任一满足即可）
    const userPermissions = userInfo.permissions || []
    const userRole = userInfo.role

    return value.some(item => {
      // 检查权限
      if (userPermissions.includes(item) || userPermissions.includes('*')) {
        return true
      }

      // 检查角色
      if (userRole === item) {
        return true
      }

      return false
    })
  }
  
  if (typeof value === 'object') {
    // 检查复杂权限条件
    if (value.role) {
      return userInfo.role === value.role
    }
    
    if (value.anyRole && Array.isArray(value.anyRole)) {
      return value.anyRole.includes(userInfo.role)
    }
    
    if (value.allRoles && Array.isArray(value.allRoles)) {
      return value.allRoles.every(role => userInfo.role === role)
    }
    
    if (value.permission) {
      const userPermissions = userInfo.permissions || []
      return userPermissions.includes(value.permission) || userPermissions.includes('*')
    }
    
    if (value.anyPermission && Array.isArray(value.anyPermission)) {
      const userPermissions = userInfo.permissions || []
      return value.anyPermission.some(permission => 
        userPermissions.includes(permission) || userPermissions.includes('*')
      )
    }
    
    if (value.allPermissions && Array.isArray(value.allPermissions)) {
      const userPermissions = userInfo.permissions || []
      return value.allPermissions.every(permission => 
        userPermissions.includes(permission) || userPermissions.includes('*')
      )
    }
  }
  
  return false
}

// 角色指令
export const role = {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    const userInfo = userStore.userInfo
    
    if (value) {
      const hasRole = checkRole(value, userInfo)
      if (!hasRole) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  }
}

// 检查角色
function checkRole(value, userInfo) {
  if (!userInfo || !userInfo.role) {
    return false
  }
  
  if (typeof value === 'string') {
    return userInfo.role === value
  }
  
  if (Array.isArray(value)) {
    return value.includes(userInfo.role)
  }
  
  return false
} 